package pl.poznan.put.cs.idss.particlefilter.ui;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class Toolbox extends JFrame implements ChangeListener, ActionListener {

	private static final long serialVersionUID = 6716778850902902694L;

	final int height = 400;
	final int width = 400;

	private int particles = 0;

	private MainWindow mainWindow;

	private JSlider slider;

	private JButton restart;
	private JButton start;
	private JButton stop;

	public Toolbox(MainWindow mainWindow) throws InterruptedException,
			IOException {
		this.mainWindow = mainWindow;
		setSize(width, height);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setLocationRelativeTo(mainWindow);
		setLayout(new GridLayout(4, 1, 20, 10));
		setTitle("Zarządzanie");
		slider = new JSlider(0, 10000, 1000);
		slider.setMajorTickSpacing(2000);
		slider.setMinorTickSpacing(500);
		slider.setPaintTicks(true);
		slider.setPaintLabels(true);
		slider.setToolTipText("Liczba cząsteczek");
		slider.setValue(500);
		slider.setPaintTicks(true);
		slider.addChangeListener(this);
		slider.setVisible(true);
		restart = new JButton("Uruchom");
		restart.setVisible(true);
		restart.addActionListener(this);
		restart.setActionCommand("restart");
		start = new JButton("Wznów");
		start.setVisible(true);
		start.addActionListener(this);
		start.setActionCommand("start");
		stop = new JButton("Zatrzymaj");
		stop.setVisible(true);
		stop.addActionListener(this);
		stop.setActionCommand("stop");
		changeSliderValue();
		add(slider);
		add(restart);
		add(stop);
		add(start);
	}

	private void changeSliderValue() {
		particles = slider.getValue();
		restart.setText("Uruchom dla " + Integer.toString(particles) + " cząstek");
	}

	public void stateChanged(ChangeEvent e) {
		changeSliderValue();
	}

	public void actionPerformed(ActionEvent e) {
		if (mainWindow != null && mainWindow.getBoard() != null) {
			if (e.getActionCommand().equals("restart")) {
				mainWindow.getBoard().stop();
				try {
					mainWindow.getBoard().setParticleFilter(particles);
					mainWindow.getBoard().start();
				} catch (Exception ex) {
				}
			} else if (e.getActionCommand().equals("stop")) {
				mainWindow.getBoard().stop();
			} else if (e.getActionCommand().equals("start")) {
				mainWindow.getBoard().start();
			} else {
				JOptionPane.showMessageDialog(this, "Akcja nieobsługiwana");
			}
		}

	}
}
